package com.baseframe.score.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baseframe.auth.utils.AuthUtil;
import com.baseframe.mybatis.utils.PageInfo;
import com.baseframe.mybatis.utils.PageUtil;
import com.baseframe.score.entity.SnsScoreUser;
import com.baseframe.score.entity.request.SnsScoreUserRequest;
import com.baseframe.score.entity.vo.SnsScoreUserVO;
import com.baseframe.score.service.SnsScoreUserService;
import com.baseframe.score.mapper.SnsScoreUserMapper;
import com.baseframe.tool.result.R;
import org.springframework.stereotype.Service;

/**

* @description 针对表【sns_score_user(用户积分表)】的数据库操作Service实现
* @createDate 2023-06-26 00:45:34
*/
@Service
public class SnsScoreUserServiceImpl extends ServiceImpl<SnsScoreUserMapper, SnsScoreUser>
    implements SnsScoreUserService{

    @Override
    public R<Object> changeScore(SnsScoreUserRequest request) {
        SnsScoreUser snsScoreUser = this.getById(request.getId());


        if (request.getChangeType() == 1){ //增加
            return this.update(new LambdaUpdateWrapper<SnsScoreUser>()
                    .eq(SnsScoreUser::getId,request.getId())
                    .set(SnsScoreUser::getAccrueTotal,snsScoreUser.getAccrueTotal()+request.getChangeValue())
                    .set(SnsScoreUser::getResidue,snsScoreUser.getResidue()+request.getChangeValue())
            )?R.success():R.fail();
        }
        if (snsScoreUser.getResidue()<request.getChangeValue()){
            return R.fail("剩余积分不足，修改失败~");
        }
        return this.update(new LambdaUpdateWrapper<SnsScoreUser>()
                .eq(SnsScoreUser::getId,request.getId())
                .set(SnsScoreUser::getResidue,snsScoreUser.getResidue()-request.getChangeValue())
        )?R.success():R.fail();
    }

    @Override
    public Page<SnsScoreUserVO> snsScoreUserPage(PageInfo pageInfo, SnsScoreUserRequest request) {
        Page<SnsScoreUserVO> page = PageUtil.buildPage(pageInfo, SnsScoreUserVO.class);
        return this.getBaseMapper().snsScoreUserPage(page,request);
    }

    @Override
    public SnsScoreUserVO getUserScoreDetails() {
        return this.getBaseMapper().getUserScoreDetailsByUserId(AuthUtil.getUserId());
    }

    @Override
    public boolean increaseScore(Long userId, Integer rewardValue) {
        return this.getBaseMapper().increaseScore(userId,rewardValue);
    }
}




